# -*- coding:utf-8 -*- 
import os, re
#定义标识
flag=0  #判断是否在自定义条目内,以#Custom_start开头，以#Custom_end结尾
hasCustom=0 #判断是否有自定义标签
#打开下载的hosts文件
fin = open( 'hosts.tmp', "r")
hosts_list = fin.readlines()
fin.close()
delList=[]
for line in hosts_list:
    if re.match('#Custom_start(\\[rn])*',line):
        flag=1
    elif flag == 0:
        delList.append(line) #保存要删除的条目
    elif re.match('#Custom_end(\\[rn])*',line):
        if flag == 1:
            hasCustom = 1
            flag=0
for deline in delList:
    hosts_list.remove(deline)
fout = open( 'hosts.tmp', "w")
fhost = open('hosts.latest',"r")
new_hosts = fhost.readlines()
#保留自定义
if hasCustom == 0:
    fout.writelines("#Custom_start\r\n#Custom_end\r\n")
elif hasCustom == 1:
    fout.writelines(hosts_list)
fout.writelines(new_hosts)      #追加下载的hosts文件
fout.close()

